﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace WiMo.Games.GameEngine.WP7S
{
    public class Stopwatch
    {
        private bool _isRunning;
        private int _startTick;
        private int _elapsed;
        /// <summary>
        /// Initializes a new instance of the Stopwatch class.
        /// </summary>
        public Stopwatch()
        {
            _isRunning = false;
        }

        public static Stopwatch StartNew()
        {
            var sw = new Stopwatch();
            sw.Start();
            return sw;
        }

        public void Start()
        {
            if (!_isRunning)
            {
                _startTick = Environment.TickCount;
                _isRunning = true;
            }
        }

        public void Reset()
        {
            _elapsed = 0;
            _isRunning = false;
            _startTick = 0;
        }

        public void Stop()
        {
            if (_isRunning)
            {
                _elapsed += Environment.TickCount - _startTick;
                _isRunning = false;
            }
        }

        public bool IsRunning
        {
            get { return _isRunning; }
        }

        public TimeSpan Elapsed
        {
            get { return TimeSpan.FromMilliseconds(GetCurrentElapsed()); }
        }

        public long ElapsedMilliseconds
        {
            get { return GetCurrentElapsed(); }
        }

        private long GetCurrentElapsed()
        {
            return this._elapsed + (IsRunning ? (Environment.TickCount - _startTick) : 0);
        }
    }
}
